{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Audio I/O\n\nThis tutorial shows how to use TorchAudio's basic I/O API to load audio files\ninto PyTorch's Tensor object, and save Tensor objects to audio files.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nimport torchaudio\n\nprint(torch.__version__)\nprint(torchaudio.__version__)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Preparation\n\nFirst, we import the modules and download the audio assets we use in this tutorial.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>When running this tutorial in Google Colab, install the required packages\n   with the following:\n\n   .. code::\n\n      !pip install boto3</p></div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import io\nimport os\nimport tarfile\nimport tempfile\n\nimport boto3\nimport matplotlib.pyplot as plt\nimport requests\nfrom botocore import UNSIGNED\nfrom botocore.config import Config\nfrom IPython.display import Audio\nfrom torchaudio.utils import download_asset\n\nSAMPLE_GSM = download_asset(\"tutorial-assets/steam-train-whistle-daniel_simon.gsm\")\nSAMPLE_WAV = download_asset(\"tutorial-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\")\nSAMPLE_WAV_8000 = download_asset(\"tutorial-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042-8000hz.wav\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Querying audio metadata\n\nFunction :py:func:`torchaudio.info` fetches audio metadata.\nYou can provide a path-like object or file-like object.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "metadata = torchaudio.info(SAMPLE_WAV)\nprint(metadata)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Where\n\n-  ``sample_rate`` is the sampling rate of the audio\n-  ``num_channels`` is the number of channels\n-  ``num_frames`` is the number of frames per channel\n-  ``bits_per_sample`` is bit depth\n-  ``encoding`` is the sample coding format\n\n``encoding`` can take on one of the following values:\n\n-  ``\"PCM_S\"``: Signed integer linear PCM\n-  ``\"PCM_U\"``: Unsigned integer linear PCM\n-  ``\"PCM_F\"``: Floating point linear PCM\n-  ``\"FLAC\"``: Flac, [Free Lossless Audio\n   Codec](https://xiph.org/flac/)_\n-  ``\"ULAW\"``: Mu-law,\n   [[wikipedia](https://en.wikipedia.org/wiki/%CE%9C-law_algorithm)_]\n-  ``\"ALAW\"``: A-law\n   [[wikipedia](https://en.wikipedia.org/wiki/A-law_algorithm)_]\n-  ``\"MP3\"`` : MP3, MPEG-1 Audio Layer III\n-  ``\"VORBIS\"``: OGG Vorbis [[xiph.org](https://xiph.org/vorbis/)_]\n-  ``\"AMR_NB\"``: Adaptive Multi-Rate\n   [[wikipedia](https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_audio_codec)_]\n-  ``\"AMR_WB\"``: Adaptive Multi-Rate Wideband\n   [[wikipedia](https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_Wideband)_]\n-  ``\"OPUS\"``: Opus [[opus-codec.org](https://opus-codec.org/)_]\n-  ``\"GSM\"``: GSM-FR\n   [[wikipedia](https://en.wikipedia.org/wiki/Full_Rate)_]\n-  ``\"HTK\"``: Single channel 16-bit PCM\n-  ``\"UNKNOWN\"`` None of above\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Note**\n\n-  ``bits_per_sample`` can be ``0`` for formats with compression and/or\n   variable bit rate (such as MP3).\n-  ``num_frames`` can be ``0`` for GSM-FR format.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "metadata = torchaudio.info(SAMPLE_GSM)\nprint(metadata)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Querying file-like object\n\n:py:func:`torchaudio.info` works on file-like objects.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "url = \"https://download.pytorch.org/torchaudio/tutorial-assets/steam-train-whistle-daniel_simon.wav\"\nwith requests.get(url, stream=True) as response:\n    metadata = torchaudio.info(response.raw)\nprint(metadata)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>When passing a file-like object, ``info`` does not read\n   all of the underlying data; rather, it reads only a portion\n   of the data from the beginning.\n   Therefore, for a given audio format, it may not be able to retrieve the\n   correct metadata, including the format itself. In such case, you\n   can pass ``format`` argument to specify the format of the audio.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Loading audio data\n\nTo load audio data, you can use :py:func:`torchaudio.load`.\n\nThis function accepts a path-like object or file-like object as input.\n\nThe returned value is a tuple of waveform (``Tensor``) and sample rate\n(``int``).\n\nBy default, the resulting tensor object has ``dtype=torch.float32`` and\nits value range is ``[-1.0, 1.0]``.\n\nFor the list of supported format, please refer to [the torchaudio\ndocumentation](https://pytorch.org/audio)_.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "waveform, sample_rate = torchaudio.load(SAMPLE_WAV)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_waveform(waveform, sample_rate):\n    waveform = waveform.numpy()\n\n    num_channels, num_frames = waveform.shape\n    time_axis = torch.arange(0, num_frames) / sample_rate\n\n    figure, axes = plt.subplots(num_channels, 1)\n    if num_channels == 1:\n        axes = [axes]\n    for c in range(num_channels):\n        axes[c].plot(time_axis, waveform[c], linewidth=1)\n        axes[c].grid(True)\n        if num_channels > 1:\n            axes[c].set_ylabel(f\"Channel {c+1}\")\n    figure.suptitle(\"waveform\")\n    plt.show(block=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plot_waveform(waveform, sample_rate)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_specgram(waveform, sample_rate, title=\"Spectrogram\"):\n    waveform = waveform.numpy()\n\n    num_channels, num_frames = waveform.shape\n\n    figure, axes = plt.subplots(num_channels, 1)\n    if num_channels == 1:\n        axes = [axes]\n    for c in range(num_channels):\n        axes[c].specgram(waveform[c], Fs=sample_rate)\n        if num_channels > 1:\n            axes[c].set_ylabel(f\"Channel {c+1}\")\n    figure.suptitle(title)\n    plt.show(block=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plot_specgram(waveform, sample_rate)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Audio(waveform.numpy()[0], rate=sample_rate)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Loading from file-like object\n\nThe I/O functions support file-like objects.\nThis allows for fetching and decoding audio data from locations\nwithin and beyond the local file system.\nThe following examples illustrate this.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Load audio data as HTTP request\nurl = \"https://download.pytorch.org/torchaudio/tutorial-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nwith requests.get(url, stream=True) as response:\n    waveform, sample_rate = torchaudio.load(response.raw)\nplot_specgram(waveform, sample_rate, title=\"HTTP datasource\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Load audio from tar file\ntar_path = download_asset(\"tutorial-assets/VOiCES_devkit.tar.gz\")\ntar_item = \"VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nwith tarfile.open(tar_path, mode=\"r\") as tarfile_:\n    fileobj = tarfile_.extractfile(tar_item)\n    waveform, sample_rate = torchaudio.load(fileobj)\nplot_specgram(waveform, sample_rate, title=\"TAR file\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Load audio from S3\nbucket = \"pytorch-tutorial-assets\"\nkey = \"VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nclient = boto3.client(\"s3\", config=Config(signature_version=UNSIGNED))\nresponse = client.get_object(Bucket=bucket, Key=key)\nwaveform, sample_rate = torchaudio.load(response[\"Body\"])\nplot_specgram(waveform, sample_rate, title=\"From S3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Tips on slicing\n\nProviding ``num_frames`` and ``frame_offset`` arguments restricts\ndecoding to the corresponding segment of the input.\n\nThe same result can be achieved using vanilla Tensor slicing,\n(i.e.\u00a0``waveform[:, frame_offset:frame_offset+num_frames]``). However,\nproviding ``num_frames`` and ``frame_offset`` arguments is more\nefficient.\n\nThis is because the function will end data acquisition and decoding\nonce it finishes decoding the requested frames. This is advantageous\nwhen the audio data are transferred via network as the data transfer will\nstop as soon as the necessary amount of data is fetched.\n\nThe following example illustrates this.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Illustration of two different decoding methods.\n# The first one will fetch all the data and decode them, while\n# the second one will stop fetching data once it completes decoding.\n# The resulting waveforms are identical.\n\nframe_offset, num_frames = 16000, 16000  # Fetch and decode the 1 - 2 seconds\n\nurl = \"https://download.pytorch.org/torchaudio/tutorial-assets/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nprint(\"Fetching all the data...\")\nwith requests.get(url, stream=True) as response:\n    waveform1, sample_rate1 = torchaudio.load(response.raw)\n    waveform1 = waveform1[:, frame_offset : frame_offset + num_frames]\n    print(f\" - Fetched {response.raw.tell()} bytes\")\n\nprint(\"Fetching until the requested frames are available...\")\nwith requests.get(url, stream=True) as response:\n    waveform2, sample_rate2 = torchaudio.load(response.raw, frame_offset=frame_offset, num_frames=num_frames)\n    print(f\" - Fetched {response.raw.tell()} bytes\")\n\nprint(\"Checking the resulting waveform ... \", end=\"\")\nassert (waveform1 == waveform2).all()\nprint(\"matched!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Saving audio to file\n\nTo save audio data in formats interpretable by common applications,\nyou can use :py:func:`torchaudio.save`.\n\nThis function accepts a path-like object or file-like object.\n\nWhen passing a file-like object, you also need to provide argument ``format``\nso that the function knows which format it should use. In the\ncase of a path-like object, the function will infer the format from\nthe extension. If you are saving to a file without an extension, you need\nto provide argument ``format``.\n\nWhen saving WAV-formatted data, the default encoding for ``float32`` Tensor\nis 32-bit floating-point PCM. You can provide arguments ``encoding`` and\n``bits_per_sample`` to change this behavior. For example, to save data\nin 16-bit signed integer PCM, you can do the following.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p></p></div>\n\nSaving data in encodings with a lower bit depth reduces the\nresulting file size but also precision.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "waveform, sample_rate = torchaudio.load(SAMPLE_WAV)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def inspect_file(path):\n    print(\"-\" * 10)\n    print(\"Source:\", path)\n    print(\"-\" * 10)\n    print(f\" - File size: {os.path.getsize(path)} bytes\")\n    print(f\" - {torchaudio.info(path)}\")\n    print()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Save without any encoding option.\nThe function will pick up the encoding which\nthe provided data fit\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with tempfile.TemporaryDirectory() as tempdir:\n    path = f\"{tempdir}/save_example_default.wav\"\n    torchaudio.save(path, waveform, sample_rate)\n    inspect_file(path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Save as 16-bit signed integer Linear PCM\nThe resulting file occupies half the storage but loses precision\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with tempfile.TemporaryDirectory() as tempdir:\n    path = f\"{tempdir}/save_example_PCM_S16.wav\"\n    torchaudio.save(path, waveform, sample_rate, encoding=\"PCM_S\", bits_per_sample=16)\n    inspect_file(path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ":py:func:`torchaudio.save` can also handle other formats.\nTo name a few:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "formats = [\n    \"flac\",\n    \"vorbis\",\n    \"sph\",\n    \"amb\",\n    \"amr-nb\",\n    \"gsm\",\n]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "waveform, sample_rate = torchaudio.load(SAMPLE_WAV_8000)\nwith tempfile.TemporaryDirectory() as tempdir:\n    for format in formats:\n        path = f\"{tempdir}/save_example.{format}\"\n        torchaudio.save(path, waveform, sample_rate, format=format)\n        inspect_file(path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Saving to file-like object\n\nSimilar to the other I/O functions, you can save audio to file-like\nobjects. When saving to a file-like object, argument ``format`` is\nrequired.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "waveform, sample_rate = torchaudio.load(SAMPLE_WAV)\n\n# Saving to bytes buffer\nbuffer_ = io.BytesIO()\ntorchaudio.save(buffer_, waveform, sample_rate, format=\"wav\")\n\nbuffer_.seek(0)\nprint(buffer_.read(16))"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}